<template>
  <div>
    <h3>商品管理 - 修改商品</h3>
    <el-form :model="formData" ref="formRef" label-width="120px" :rules="rules">
      <el-form-item label="选择店铺" prop="merchantId">
        <el-select v-model="formData.merchantId" placeholder="请选择店铺" @change="getProductsByMerchant">
          <el-option
              v-for="merchant in merchantList"
              :key="merchant.id"
              :label="merchant.shopName"
              :value="merchant.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择商品" prop="productId">
        <el-select v-model="formData.productId" placeholder="请选择商品" @change="fillProductInfo">
          <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.name"
              :value="product.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="formData.description" placeholder="请输入商品描述"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input v-model="formData.price" placeholder="请输入商品价格"></el-input>
      </el-form-item>
      <el-form-item label="商品库存" prop="stock">
        <el-input v-model="formData.stock" placeholder="请输入商品库存"></el-input>
      </el-form-item>
      <el-form-item label="商品单位" prop="unit">
        <el-input v-model="formData.unit" placeholder="请输入商品单位"></el-input>
      </el-form-item>
      <el-form-item label="商品产地" prop="origin">
        <el-input v-model="formData.origin" placeholder="请输入商品产地"></el-input>
      </el-form-item>
      <el-form-item label="商品图片">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="customImageUpload"
        >
          <div class="avatar-wrapper">
            <img
                v-if="formData.imageUrls"
                :src="formData.imageUrls"
                class="avatar-image"
            />
            <div v-else class="avatar-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span class="upload-text">上传商品图片</span>
            </div>
            <div class="upload-mask">
              <el-icon class="upload-icon"><Edit /></el-icon>
              <span class="upload-text">更换图片</span>
            </div>
          </div>
          <div class="mt-2 text-sm text-gray-500">商品图片为必填项，不上传将使用默认图片</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateProduct">确认修改</el-button>
        <!-- 新增上架和下架按钮 -->
        <el-button type="success" @click="putOnProduct">上架商品</el-button>
        <el-button type="danger" @click="putOffProduct">下架商品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { Plus, Edit } from '@element-plus/icons-vue'

// 从 localStorage 获取用户信息
const userStr = localStorage.getItem('merchant');
const user = userStr ? JSON.parse(userStr) : null;

// 默认图片
const defaultImage = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 定义表单数据
const formData = ref({
  id: null, // 添加商品ID
  merchantId: null,
  productId: null,
  name: '',
  description: '',
  price: '',
  stock: '',
  unit: '',
  origin: '',
  imageUrls: ''
});

// 表单验证规则
const rules = reactive({
  merchantId: [
    { required: true, message: '请选择店铺', trigger: 'change' }
  ],
  productId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '商品名称长度在2 - 100个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { max: 255, message: '商品描述不能超过255个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入正确的库存数量', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入商品单位', trigger: 'blur' },
    { max: 20, message: '商品单位不能超过20个字符', trigger: 'blur' }
  ],
  origin: [
    { required: true, message: '请输入商品产地', trigger: 'blur' },
    { max: 50, message: '商品产地不能超过50个字符', trigger: 'blur' }
  ],
  imageUrls: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ]
});

// 表单引用
const formRef = ref(null);

// 定义店铺列表
const merchantList = ref([]);

// 定义商品列表
const productList = ref([]);

// 获取店铺列表
const getMerchantList = async () => {
  try {
    // 发送查看店铺请求
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });
    if (response.data.code === 2000) {
      merchantList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取店铺列表失败');
    }
  } catch (error) {
    console.error('获取店铺列表失败:', error);
    ElMessage.error('获取店铺列表失败，请稍后重试');
  }
};

// 根据店铺 ID 获取商品列表
const getProductsByMerchant = async () => {
  const merchantId = formData.value.merchantId;
  if (!merchantId) return;
  try {
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selProduct`, {
      params: { merchantId },
      withCredentials: true
    });
    if (response.data.code === 2000) {
      productList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败，请稍后重试');
  }
};

// 填充商品信息到表单
const fillProductInfo = () => {
  const productId = formData.value.productId;
  const selectedProduct = productList.value.find(product => product.id === productId);
  if (selectedProduct) {
    formData.value.id = selectedProduct.id; // 添加商品ID
    formData.value.name = selectedProduct.name;
    formData.value.description = selectedProduct.description;
    formData.value.price = selectedProduct.price.toString(); // 转为字符串
    formData.value.stock = selectedProduct.stock.toString(); // 转为字符串
    formData.value.unit = selectedProduct.unit;
    formData.value.origin = selectedProduct.origin;
    formData.value.imageUrls = selectedProduct.imageUrls || defaultImage;
  }
};

// 自定义图片上传
const customImageUpload = async (options) => {
  const { file } = options;
  try {
    const formDataUpload = new FormData();
    formDataUpload.append('file', file);
    formDataUpload.append('userId', user?.id || '123');

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formDataUpload, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    });

    if (response.data.code === 2000) {
      ElMessage.success('图片上传成功');
      formData.value.imageUrls = response.data.data;
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error) {
    ElMessage.error('上传出错：' + error.message);
    throw error;
  }
};

// 上传前校验
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }

  return isImage && isLt5M;
};

// 定义修改商品方法
const updateProduct = async () => {
  // 表单验证
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请完善商品信息');
      return;
    }

    // 如果没有上传图片，使用默认图片
    // if (!formData.value.imageUrl) {
    //   formData.value.imageUrl = defaultImage;
    // }

    // 创建一个临时对象进行类型转换
    const productData = {
      ...formData.value,
      price: parseFloat(formData.value.price), // 转为数字
      stock: parseInt(formData.value.stock) // 转为整数
    };

    console.log('提交的数据:', productData); // 调试用
    //productData.imageUrls = formData.value.imageUrl;

    // 使用转换后的对象发送请求
    axios.post(`${BASE_URL}/api/v1/merchant/reviseProduct`, productData, {
      withCredentials: true
    })
        .then(response => {
          console.log('响应数据:', response); // 调试用
          if (response.data.code === 2000) {
            ElMessage.success('商品修改成功');
            // 清空表单
            formData.value = {
              id: null,
              merchantId: null,
              productId: null,
              name: '',
              description: '',
              price: '',
              stock: '',
              unit: '',
              origin: '',
              imageUrls: ''
            };
            productList.value = [];
          } else {
            ElMessage.error(response.data.msg || '修改商品失败');
          }
        })
        .catch(error => {
          console.error('修改商品失败:', error);
          if (error.response) {
            ElMessage.error(`错误 ${error.response.status}: ${error.response.data.msg || '服务器错误'}`);
          } else {
            ElMessage.error('修改商品失败，请稍后重试');
          }
        });
  });
};

// 商品上架方法
const putOnProduct = async () => {
  if (!formData.value.merchantId || !formData.value.id) {
    ElMessage.error('请选择店铺和商品');
    return;
  }
  const productPutDto = {
    merchantId: formData.value.merchantId,
    status: 1,
    id: formData.value.id
  };
  try {
    const response = await axios.post(`${BASE_URL}/api/v1/merchant/isPutProduct`, productPutDto, {
      withCredentials: true
    });
    if (response.data.code === 2000) {
      ElMessage.success('商品上架成功');
    } else {
      ElMessage.error(response.data.msg || '商品上架失败');
    }
  } catch (error) {
    console.error('商品上架失败:', error);
    if (error.response) {
      ElMessage.error(`错误 ${error.response.status}: ${error.response.data.msg || '服务器错误'}`);
    } else {
      ElMessage.error('商品上架失败，请稍后重试');
    }
  }
};

// 商品下架方法
const putOffProduct = async () => {
  if (!formData.value.merchantId || !formData.value.id) {
    ElMessage.error('请选择店铺和商品');
    return;
  }
  const productPutDto = {
    merchantId: formData.value.merchantId,
    status: 2,
    id: formData.value.id
  };
  try {
    const response = await axios.post(`${BASE_URL}/api/v1/merchant/isPutProduct`, productPutDto, {
      withCredentials: true
    });
    if (response.data.code === 2000) {
      ElMessage.success('商品下架成功');
    } else {
      ElMessage.error(response.data.msg || '商品下架失败');
    }
  } catch (error) {
    console.error('商品下架失败:', error);
    if (error.response) {
      ElMessage.error(`错误 ${error.response.status}: ${error.response.data.msg || '服务器错误'}`);
    } else {
      ElMessage.error('商品下架失败，请稍后重试');
    }
  }
};

// 页面挂载时获取店铺列表
onMounted(() => {
  if (user) {
    getMerchantList();
  } else {
    ElMessage.error('请先登录');
  }
});
</script>

<style scoped>
.avatar-uploader {
  --el-avatar-size: 178px;
}

.avatar-wrapper {
  position: relative;
  width: var(--el-avatar-size);
  height: var(--el-avatar-size);
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

.mt-2 {
  margin-top: 0.5rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.text-gray-500 {
  color: #6b7280;
}
</style>